#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->treeWidget->setHeaderLabel("动物");
    QTreeWidgetItem*item1=new QTreeWidgetItem();
    item1->setText(0,"猫");
     //新增顶层节点
    ui->treeWidget->addTopLevelItem(item1);

    QTreeWidgetItem*item2=new QTreeWidgetItem();
    item2->setText(0,"狗");
    //新增顶层节点
    ui->treeWidget->addTopLevelItem(item2);

    QTreeWidgetItem*item3=new QTreeWidgetItem();
    item3->setText(0,"鸡");
    ui->treeWidget->addTopLevelItem(item3);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    //获取输入框内容
    const QString s=ui->lineEdit->text();
    if(s.isEmpty())
    {
        return;
    }
    //添加到顶层节点中
    QTreeWidgetItem*item=new QTreeWidgetItem();
    item->setText(0,s);
    ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_pushButton_2_clicked()
{
    //获取输入框的内容
    const QString s=ui->lineEdit->text();
    if(s.isEmpty())
    {
        return;
    }
    //获取当前选中的节点
    QTreeWidgetItem*currentitem=ui->treeWidget->currentItem();
    if(currentitem==NULL)
    {
        return;
    }
    //构建出新的item
    QTreeWidgetItem*newitem=new QTreeWidgetItem();
    newitem->setText(0,s);
    currentitem->addChild(newitem);

    //展开父节点
    currentitem->setExpanded(false);

}

void Widget::on_pushButton_3_clicked()
{
    //删除
    //获取当前选中的节点
    QTreeWidgetItem*currentitem=ui->treeWidget->currentItem();
    //删除
    QTreeWidgetItem*parent=currentitem->parent();
    if(parent==NULL)
    {
        //顶层节点
        int index=ui->treeWidget->indexOfTopLevelItem(currentitem);
        ui->treeWidget->takeTopLevelItem(index);
    }
    else
    {
        //非顶层节点
        parent->removeChild(currentitem);
    }
}
